package 栈;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import java.util.List;

/**
 * 输入一个逆波兰表达式，使用栈，计算其结果
 */
public class 逆波兰计算器 {

    public static void main(String[] args) {
        //逆波兰表达式
        //(3+4)*5-6  -> 3 4 + 5 * 6 -
//        String suffixExpression = "3 4 + 5 * 6 -";
        String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";  //76
        System.out.println(new 逆波兰计算器().suffixCalculate(suffixExpression));

    }

    /**
     * 思路：
     * 从左至右扫描表达式，遇到数字时，将数字压入栈，遇到运算符时，弹出
     * 栈顶的两个数，用运算符对它们进行计算，并将结果入栈，重复，至表达
     * 式的最右端
     *
     * @param expression
     * @return
     */
    public int suffixCalculate(String expression) {
        Deque<Integer> stack = new ArrayDeque<>();
        String[] strs = expression.split(" ");
        List<String> list = Arrays.asList(strs);
        for (String str : list) {
            if (str.length() > 1 || Character.isDigit(str.charAt(0))) {
                stack.addFirst(Integer.valueOf(str));
            } else {
                Integer after = stack.pollFirst();
                Integer before = stack.pollFirst();
                stack.addFirst(operate(after, before, str.charAt(0)));
            }
        }
        return stack.peek();
    }

    public static int operate(int after, int before, int oper) {
        int ans = 0;  //用于存放计算的结果
        switch (oper) {
            case '+':
                ans = before + after;
                break;
            case '-':
                ans = before - after;
                break;
            case '*':
                ans = before * after;
                break;
            case '/':
                ans = before / after;
                break;
            default:
                System.out.println();
                break;
        }
        return ans;
    }

}
